package cn.topevery.garden.framework.util;

import com.alibaba.fastjson.JSONObject;
import hw.topevery.fmp.runtime.FmpRuntime;
import hw.topevery.framework.omi.RsResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class HttpUtils {

    public static Map urlencodedPost(String url, String api, Map<String, Object> params) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
        for (String s : params.keySet()) {
            postParameters.set(s, params.get(s));
        }
        postParameters.add("GTOKEN", "8DA3B0BE75DF88DA0CECCDC98A76897F");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters, headers);
        return restTemplate.postForObject(url + api, r, Map.class);
    }

    public static JSONObject doPost(String url, String params) {
        RestTemplate client = new RestTemplate();
        URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();
        log.info("参数:" + params);
        RequestEntity<String> requestEntity = RequestEntity.post(uri)
                .accept(MediaType.APPLICATION_JSON)
                .header("Content-Type", "application/json")
                .body(params);
        JSONObject data = null;
        try {

            ResponseEntity<String> exchange = client.exchange(requestEntity, String.class);

            data = JSONObject.parseObject(exchange.getBody());
            log.info("结果：" + data.toJSONString());
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("请求失败", ex);
        }
        return data;
    }

    public static Map getFileId(String fileUrl) throws IOException {
        Map<String, String> map = new HashMap<>();
        RestTemplate client = new RestTemplate();
        RequestCallback requestCallback = request -> request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
        client.execute(fileUrl, HttpMethod.GET, requestCallback, clientHttpResponse -> {
            String regName = "[^\\/\\\\]+$";
            String reg = "[^\\.]\\w*$";
            Matcher nameMatcher = Pattern.compile(regName).matcher(fileUrl);
            Matcher matcher = Pattern.compile(reg).matcher(fileUrl);
            String filename = null;
            if (nameMatcher.find()) {
                filename = nameMatcher.group();
                map.put("fileName", filename);
            }
            String fileExtension = null;
            if (matcher.find()) {
                fileExtension = matcher.group();
                map.put("fileExtension", fileExtension);
            }

            RsResult rsResult = null;
            try {
                rsResult = FmpRuntime.upload("file", "image/png", filename, clientHttpResponse.getBody());
                if (rsResult.success) {
                    map.put("fileId", rsResult.dataJsonVal);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return clientHttpResponse.getBody();
        });

        return map;
    }

}
